<template>
  <div ref="tableWarp" class="tableWarp">
    <!-- 操作按钮区域 -->
    <slot name="extra_" slot="extra"></slot>
    <div class="table-operator">
      <a-row type="flex" :gutter="24" justify="space-between">
        <a-col :xl="16" :lg="16" :md="16" :sm="16" >
          <a-button type="primary" icon="download" >导出</a-button>
          <h5 style="display:inline-block;">{{cggraphreportData.head.annotation}}</h5>
        </a-col>
        <a-col :xl="4" :lg="4" :md="4" :sm="4" style="text-align:end">
          <a-switch checked-children="分页" un-checked-children="分页" v-model="ipagination"/>
        </a-col>
      </a-row>
    </div>
    <a-table
      size="middle"
      bordered
      :rowKey="(record, index) => index"
      :columns="columns"
      :data-source="getTableAddTotalRow"
      :pagination="ipagination"
      :scroll="{x:getTableScroll}"
    >
      <template v-for="(key,i) in Object.keys(customRender)" :slot="key" slot-scope="text, record, index">
        <div class="custom-render" :key="i" @click="addComment(text,record,index,$event)" v-html="customRender[key](text, record)"></div>
      </template>
    </a-table>
  </div>
</template>
<script>
import { filterDictTextByCache } from '@/components/dict/JDictSelectUtil'
export default {
  name: 'GraphreportAutoTable',
  computed: {
    getTableAddTotalRow() { // 根据配置获取表格数据
      let tableDataSource_
      if (this.cggraphreportData.head.dataType === 'json') {
        tableDataSource_ = JSON.parse(JSON.stringify(this.chartData))
      } else if (this.cggraphreportData.head.dataType === 'sql' || this.cggraphreportData.head.dataType === 'bean') {
        tableDataSource_ = JSON.parse(JSON.stringify(this.cggraphreportData.data.data))
      }
      if (!this.isTotal) {
        return tableDataSource_
      }
      const numKey = 'rowIndex'
      const totalRow = { [numKey]: '合计' }
      this.columns.forEach(column => {
        const { key, dataIndex } = column
        if (![key, dataIndex].includes(numKey)) {
          let total = 0
          tableDataSource_.forEach(data => {
            total += /^\d+\.?\d?$/.test(data[dataIndex]) ? Number.parseFloat(data[dataIndex]) : Number.NaN
          })
          if (Number.isNaN(total) || !column.isTotal) {
            total = '-'
          }
          totalRow[dataIndex] = total
        }
      })
      tableDataSource_.push(totalRow)
      return tableDataSource_
    },
    getTableScroll() {
      const width = this.columns.length * 100 - 40
      // 解决表格列分配宽度小于表格宽度时 多一列bug
      if (width < this.tableWarpWidth) {
        this.columns.forEach(function(item) {
          if (item.dataIndex !== 'rowIndex') {
            delete item.width
          }
        })
      }
      return width > this.tableWarpWidth ? width : false
    }
  },
  data() {
    return {
      columns: [], // 需要渲染的表头
      rowIndexColumns: {// 序号列头
        title: '#',
        dataIndex: 'rowIndex',
        width: 60,
        align: 'center',
        fixed: 'left',
        customRender: function(text, r, index) {
          return parseInt(index) + 1
        }
      },
      rowIndexTotalColumns: {// 序号列头
        title: '#',
        dataIndex: 'rowIndex',
        width: 60,
        align: 'center',
        fixed: 'left',
        customRender: function(text, r, index) {
          return (text !== '合计') ? (parseInt(index) + 1) : text
        }
      },
      customRender: {},
      ipagination: true,
      spinning: true,
      tableWarpWidth: 0, // 判断table是否超宽
      isTotal: false // 判断是否合计
    }
  },
  props: ['items', 'cggraphreportData', 'chartData'],
  watch: {
    items: {
      handler(val, oldVal) {
        this.getColunms()
      },
      deep: true // true 深度监听
    }
  },
  mounted() {
    this.$nextTick(() => {
      if (this.$refs.tableWarp) {
        this.tableWarpWidth = this.$refs.tableWarp.offsetWidth
      }
      this.getColunms()
    })
  },
  methods: {
    getColunms() { // 根据弹窗的数据获取表格的表头
      const that = this
      that.columns = [this.rowIndexColumns]
      const items = JSON.parse(JSON.stringify(this.items))
      items.sort(function(a, b) {
        return a.orderNum - b.orderNum
      })
      items.forEach((item, i) => {
        if (item.isShow) {
          const column = {
            title: item.fieldTxt,
            align: 'center',
            dataIndex: item.fieldName,
            isTotal: item.isTotal,
            width: item.fieldWidth || 100
          }
          if (item.dictCode) {
            column.customRender = function(t, r, i) {
              return filterDictTextByCache(item.dictCode, t)
            }
          }
          if (item.jsEnhance) {
            column.scopedSlots = { customRender: column.dataIndex }
            var obj = eval('(' + item.jsEnhance + ')')
            that.customRender[column.dataIndex] = obj.customRender
          }
          that.columns.push(column)
        }
        if (item.isTotal) {
          this.isTotal = true
        }
      })
      if (this.isTotal) {
        that.columns.splice(0, 1, this.rowIndexTotalColumns)
      }
      if (that.getTableScroll) {
        this.rowIndexColumns.fixed = 'left'
      } else {
        this.rowIndexColumns.fixed = false
      }
    },
    addComment(text, record, index, $event) { // 处理js增强添加的方法  目前只支持click
      var domClick = $event.target.getAttribute('@click')
      if (domClick) {
        domClick = eval('(' + domClick + ')')
        domClick.call(this, text, record, index)
      }
    }
  }
}
</script>
<style scoped>
.ant-table td { white-space: nowrap; }
</style>
<style>
  .custom-render>*{
    display: inline-block;
    min-width: 20px;
    height: 100%;
    border-radius: 5px;
  }
  .custom-render{
    display: inline-block;
  }
</style>
